package luogu;

import java.math.BigInteger;
import java.util.Scanner;

public class P1591 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        int[][] arr = new int[t][2];
        for (int i = 0; i < t; i++) {
            for (int i1 = 0; i1 < 2; i1++) {
                arr[i][i1] = sc.nextInt();
            }
        }
        BigInteger ans = BigInteger.ONE;
        Long res = 0L;
        for (int i = 0; i < t; i++) {
            for (int j = 2; j <= arr[i][0]; j++) {
                ans = ans.multiply(BigInteger.valueOf(j));
            }
            String s = ans.toString();
            for (int k = 0; k < s.length(); k++) {
                if (s.charAt(k) == String.valueOf(arr[i][1]).charAt(0)){
                    res += 1;
                }
            }
            System.out.println(res);
            res = 0L;
            ans = BigInteger.ONE;
        }
    }
}
